package com.wxy.lianxi.springbootday01.contoller;

import com.wxy.lianxi.springbootday01.mapper.UserMapper;
import com.wxy.lianxi.springbootday01.pojo.R;
import com.wxy.lianxi.springbootday01.pojo.User;
import com.wxy.lianxi.springbootday01.pojo.dto.UserDto;
import com.wxy.lianxi.springbootday01.service.impl.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Restcontroller 用于把接口返回的对象转换为Json传给前端
 * @controller 用于页面跳转
 */
@RestController
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @PostMapping("/add")
//  @Validated注解为检验前端传来的参数书否按照Dto里设置的规则来设置,否则抛异常.
    //@requestBody会把前端传来的Json转为对象
    public R add(@Validated @RequestBody UserDto userDto){
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        userMapper.insert(user);
        return R.success(user);
    }

    /**
     * 剩下需要练的有getMapping,putMapping,deleteMapping
     *
     */
    @Autowired
    private UserService userService;

    /**
     *
     * @param userid
     * 什么都不写,就默认localhost:8088/User?userid=1 从?后传参,但是后端userid要跟前端传来
     * 的对应上,默认是@RequestParam,请求参数就是从?后传参.
     */
    @GetMapping
    public R getUserInfo(@RequestParam("aoteman") Integer userid){
        User user = userService.getById(userid);
        return R.success(user);
    }


    @PutMapping("put")
    public R putUserInfo(@RequestBody UserDto userDto){
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        userService.updateById(user);
        return R.success(null);
    }

    @DeleteMapping("delete")
    public R delete(Integer userid){
        userService.removeById(userid);
        return R.success(null);
    }



}
